import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_base/pages/test_detail/widgets/test_card_base.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

/// 视觉仪表盘组件
class TestVisualMeterBlock extends StatelessWidget {
  final Map? data;

  // final String title;
  // final String subtitle;
  // final int value; // 当前值，0-100
  // final String level; // 等级文本，如"Very high"
  // final int completionRate; // 完成率，0-100

  const TestVisualMeterBlock({
    super.key,
    required this.data,
    // required this.subtitle,
    // required this.value,
    // required this.level,
    // required this.completionRate,
  });

  @override
  Widget build(BuildContext context) {
    // title: 'Comprehensive ability',
    // subtitle: 'Comprehensive indicators',
    // value: 60,
    // level: 'Very high',
    // completionRate: 82,
    Map sourceData = data != null
        ? data!
        : {
            "meters": [
              {
                "level": "Very high",
                "max_value": 82,
                "name": "Emotional Health Index",
                "unit": "%",
                "value": 60
              }
            ],
            "title": "Comprehensive ability"
          };

    return TestCardBase(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题部分
          Text(
            'Comprehensive ability',
            style: TextStyle(
              fontFamily: 'Outfit',
              fontWeight: FontWeight.w600,
              fontSize: 14.sp,
              color: const Color(0xFF0C0A09),
              letterSpacing: 0.14,
              height: 1.26, // 17.64/14
            ),
          ),
          SizedBox(height: 4.w),
          Text(
            'Comprehensive indicators',
            style: TextStyle(
              fontFamily: 'Outfit',
              fontWeight: FontWeight.w400,
              fontSize: 12.sp,
              color: const Color(0xFF7F909F),
              height: 1.26, // 15.12/12
            ),
          ),
          SizedBox(height: 30.w),

          // 仪表盘部分
          Center(
            child: SizedBox(
              width: 246.w,
              height: 246.w,
              child: Stack(
                alignment: Alignment.center,
                children: [
                  // 浅色背景圆
                  Container(
                    width: 236.w,
                    height: 236.w,
                    decoration: const BoxDecoration(
                      shape: BoxShape.circle,
                      color: Color(0xFFFEF7F3), // 浅粉色背景
                    ),
                  ),
                  // 渐变弧线(从底部开始顺时针)
                  CustomPaint(
                    size: Size(246.w, 246.w),
                    painter: GradientArcPainter(
                      value: sourceData['meters'][0]['value'] ?? 0,
                    ),
                  ),
                  // 中心白色圆
                  Container(
                    width: 120.w,
                    height: 120.w,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: Colors.white,
                      boxShadow: [
                        BoxShadow(
                          color: const Color(0xFFFF8F79).withOpacity(0.44),
                          // 橙红色阴影
                          blurRadius: 43,
                          offset: const Offset(0, 27),
                          spreadRadius: 2,
                        ),
                      ],
                    ),
                  ),

                  // 数值和等级文本
                  Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        (sourceData['meters'][0]['value'] ?? 0).toString(),
                        style: TextStyle(
                          fontFamily: 'Outfit',
                          fontWeight: FontWeight.w500,
                          fontSize: 40.sp,
                          color: const Color(0xFF0D0D12),
                        ),
                      ),
                      SizedBox(height: 4.w),
                      Text(
                        sourceData['meters'][0]['level'] ?? '',
                        style: TextStyle(
                          fontFamily: 'Outfit',
                          fontWeight: FontWeight.w400,
                          fontSize: 16.sp,
                          color: const Color(0xFFADB5C2),
                          letterSpacing: 0.2,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),

          SizedBox(height: 30.w),

          // 底部数据指标部分
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 当前值
              Expanded(
                child: _buildDataItem('Current value',
                    (sourceData['meters'][0]['value'] ?? '0').toString()),
              ),
              SizedBox(width: 12.w),
              // 等级
              Expanded(
                child: _buildDataItem('Level',
                    (sourceData['meters'][0]['level'] ?? '').toString()),
              ),
              SizedBox(width: 12.w),
              // 完成率
              Expanded(
                child: _buildDataItem('Max Value',
                    "${sourceData['meters'][0]['max_value'] ?? ''}${sourceData['meters'][0]['unit'] ?? ''}"),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建数据指标项
  Widget _buildDataItem(String label, String value) {
    return Column(
      // crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Text(
          label,
          style: TextStyle(
            fontFamily: 'Outfit',
            fontWeight: FontWeight.w500,
            fontSize: 12.sp,
            color: const Color(0xFF7F909F),
            height: 1.26, // 15.12/12
          ),
          textAlign: TextAlign.center,
        ),
        SizedBox(height: 8.w),
        Text(
          value,
          style: TextStyle(
            fontFamily: 'Outfit',
            fontWeight: FontWeight.w600,
            fontSize: label == 'Level' ? 15.sp : 24.sp,
            color: const Color(0xFF0C0A09),
            height: 1.26,
          ),
          textAlign: TextAlign.center,
        ),
      ],
    );
  }
}

/// 渐变弧线绘制器
class GradientArcPainter extends CustomPainter {
  final int value; // 0-100之间的值

  GradientArcPainter({required this.value});

  @override
  void paint(Canvas canvas, Size size) {
    final double centerX = size.width / 2;
    final double centerY = size.height / 2;
    final double radius = size.width / 2;

    // 计算圆弧角度（根据value值，0-100%对应0-360度）
    final double sweepAngle = 2 * pi * value / 100; // 完整圆是2π
    final double startAngle = pi / 2; // 从底部开始 (π/2 = 90度)

    // 计算进度终点的位置 - 圆点指示器位置
    final double progressEndAngle = startAngle + sweepAngle;
    final double indicatorRadius = (radius + 60) / 2; // 指示器位置半径
    final double dotX = centerX + indicatorRadius * cos(progressEndAngle);
    final double dotY = centerY + indicatorRadius * sin(progressEndAngle);

    // 绘制蓝色渐变填充效果 (从圆点指示器开始，逆时针方向)
    if (value > 0) {
      // 计算渐变长度 (约45度 = π/4弧度)
      final double gradientSweepAngle = pi / 3; // 45度

      // 确保渐变长度不超过当前进度
      final double actualGradientAngle = min(gradientSweepAngle, sweepAngle);

      // 使用一系列部分扇形来创建渐变效果
      final int segments = 10; // 分段数量
      double segmentAngle = actualGradientAngle / segments;

      for (int i = 0; i < segments; i++) {
        // 从圆点指示器开始，逆时针方向计算扇形段位置
        // 注意：逆时针方向是角度减小的方向
        double segStartAngle = progressEndAngle - ((i + 1) * segmentAngle);
        double segEndAngle = progressEndAngle - (i * segmentAngle);

        // 计算当前段的透明度 - 圆点指示器处(i=0)最蓝
        // 随着逆时针远离，透明度降低
        double opacity = 0.3 - (i * 0.25 / segments); // 从0.3递减到接近0.05

        // 创建当前扇形段的路径
        final Path segmentPath = Path()
          ..moveTo(centerX, centerY)
          ..arcTo(
              Rect.fromCircle(center: Offset(centerX, centerY), radius: radius),
              segStartAngle,
              segEndAngle - segStartAngle,
              false)
          ..lineTo(centerX, centerY)
          ..close();

        // 创建填充画笔 - 使用固定颜色但透明度递减
        final Paint segmentPaint = Paint()
          ..style = PaintingStyle.fill
          ..color = Color.fromRGBO(
              169, 209, 255, opacity); // A9D1FF with variable opacity

        // 绘制当前扇形段
        canvas.drawPath(segmentPath, segmentPaint);
      }
    }

    // 定义渐变色
    final Rect gradientRect =
        Rect.fromCircle(center: Offset(centerX, centerY), radius: radius);

    // 创建画笔 - 加粗进度条
    final Paint paint = Paint()
      ..style = PaintingStyle.stroke
      ..strokeWidth = 12.0 // 加粗进度条
      ..strokeCap = StrokeCap.round;

    // 使用着色器绘制渐变的圆弧
    if (sweepAngle > 0) {
      // 创建自定义渐变
      final SweepGradient gradient = SweepGradient(
        center: Alignment.center,
        startAngle: pi / 2,
        // 从正下方开始 (90度)
        endAngle: pi / 2 + sweepAngle,
        // 仅覆盖进度弧线
        tileMode: TileMode.clamp,
        colors: const [
          Color(0x00A880DA), // 完全透明的紫色起点
          Color(0x4DA880DA), // 30% opacity (0x4D ≈ 30%)
          Color(0xFFA880DA), // 中间紫色
          Color(0xFF076EFF), // 蓝色终点
        ],

        // stops: const [0.0, 0.5, 1.0],
      );

      paint.shader = gradient.createShader(gradientRect);

      // 绘制进度弧线
      canvas.drawArc(
        Rect.fromCircle(center: Offset(centerX, centerY), radius: radius - 6),
        startAngle,
        sweepAngle,
        false,
        paint,
      );
    }

    // 在进度终点绘制小圆点指示器 - 调整位置到中间位置
    if (value > 0) {
      // 绘制外圈光晕效果
      final Paint dotGlowPaint = Paint()
        ..color = Colors.white.withOpacity(0.6)
        ..style = PaintingStyle.fill;

      canvas.drawCircle(Offset(dotX, dotY), 12.w, dotGlowPaint);

      // 绘制白色中圈
      final Paint dotOuterPaint = Paint()
        ..color = Colors.white
        ..style = PaintingStyle.fill;

      canvas.drawCircle(Offset(dotX, dotY), 9.w, dotOuterPaint);

      // 绘制内圈蓝色点
      final Paint dotInnerPaint = Paint()
        ..color = const Color(0xFF1862FE)
        ..style = PaintingStyle.fill;

      canvas.drawCircle(Offset(dotX, dotY), 6.w, dotInnerPaint);
    }
  }

  @override
  bool shouldRepaint(covariant GradientArcPainter oldDelegate) {
    return oldDelegate.value != value;
  }
}
